const app = getApp()
import {
	list,
	count
} from '../../../api/coupon'
import {
  add,
  buyNow
} from '../../../api/cart'
import {
  find
} from '../../../api/product';
import {
	buyNowForCoupon
} from '../../../api/cart'
Page({
	data: {
		winWidth: 0,
		winHeight: 0,
		swiperHeight: 0,
		currentTab: 0,
		productId:'',
		quantity:0,
		fullReductionCouponList: [
			// {
			//         shopName: "葫芦派",
			//         couponList: [{
			//                         name: "满减券",
			//                         account: 20,
			//                         limit: 200,
			//                         tag: "全品类"
			//                 },
			//                 {
			//                         name: "满减券",
			//                         account: 20,
			//                         limit: 200,
			//                         tag: "全品类"
			//                 },
			//         ]
			// },
			// {
			//         shopName: "葫芦派",
			//         couponList: [{
			//                 name: "满减券",
			//                 account: 20,
			//                 limit: 200,
			//                 tag: "全品类"
			//         }]
			// },
		],
		discountCouponList: [
			// {
			// shopName: "葫芦派",
			// couponList: [{
			//         name: "满减券",
			//         account: 8,
			//         limit: 200,
			//         tag: "全品类"
			// }]
			// }
		],
		exchangetCouponList: [
			//         {
			//         shopName: "葫芦派",
			//         couponList: [{
			//                 name: "满减券",
			//                 product: "清扬洗发露",
			//                 num: "1瓶",
			//         }]
			// }
		],
	},
	onLoad: function(options) {
		var that = this;
		/**
		 * 获取当前设备的宽高
		 */
		that.data.currentTab = options.currentTab
		this.setData({
			currentTab:that.data.currentTab
		})
	},

	onShow: function() {
		var _this = this;
		let windowHeight = 0
		wx.getSystemInfo({
			success: function(res) {
				// that.setData({
				//         winWidth: res.windowWidth,
				//         winHeight: res.windowHeight
				// });
				windowHeight = res.windowHeight
				console.info("res.windowHeight--" + res.windowHeight)
			}

		});
		var query = wx.createSelectorQuery();
		//选择id

		query.select('.coupon_choose').boundingClientRect(function(rect) {
			console.log("category-search--" + JSON.stringify(rect))
			let swiperHeight = windowHeight - rect.bottom
			console.log("swiperHeight--" + swiperHeight)
			_this.setData({
				swiperHeight: swiperHeight
			})
		}).exec()
		this.getCouponData()
	},

	//适用范围的初始化
	formatTag(value) {
		let rusult = ""
		switch (value) {
			case 0:
				rusult = "全场通用"
				break;
			case 1:
				rusult = "指定品牌"
				break;
			case 2:
				rusult = "会员专属"
				break;
			case 3:
				rusult = "指定品类"
				break;
			case 4:
				rusult = "指定商品"
				break;
			case 5:
				rusult = "指定商品兑换"
				break;
		}
		return rusult

	},

	//获取优惠券的数据
	getCouponData(callback) {
		list({
			pageSize: 1000
		}).then(
			res => {

				if (res.type == 'success') {
					if (res.data.data.length > 0) {
						let fullReductionCouponList = []
						let discountCouponList = []
						let exchangetCouponList = []
						let fullReductionShopList = []
						let discountShopList = []
						let exchangetShopList = []
						res.data.data.map((item) => {
							if (item.type == 0) {
								fullReductionShopList.push(item.mchName)
							} else if (item.type == 1) {
								discountShopList.push(item.mchName)
							} else if (item.type == 3) {
								exchangetShopList.push(item.mchName)
							}
						})
						fullReductionShopList = Array.from(new Set(fullReductionShopList))
						discountShopList = Array.from(new Set(discountShopList))
						exchangetShopList = Array.from(new Set(exchangetShopList))
						if (fullReductionShopList.length > 0) {
							fullReductionShopList.map((item) => {
								let fullReductionCouponListItem = {}
								fullReductionCouponListItem.couponList = []
								res.data.data.map((item1) => {
									if (item1.mchName == item) {
										if (item1.type == 0) {
											fullReductionCouponListItem.mchName = item1.mchName
											fullReductionCouponListItem.mchLogo = item1.mchLogo
											if (item1.endDate==null) {
												item1.endDate = "永久有效"
											} else {
												item1.endDate = this.formatDateAndTime(item1.endDate)
											}
											item1.tag = this.formatTag(item1.targetType)
											fullReductionCouponListItem.couponList.push(item1)
										}
									}
								})
								fullReductionCouponList.push(fullReductionCouponListItem)
							})
						}
						console.log(fullReductionShopList)
						if (discountShopList.length > 0) {
							discountShopList.map((item) => {
								let discountCouponListItem = {}
								discountCouponListItem.couponList = []
								res.data.data.map((item1) => {
									if (item1.mchName == item) {
										if (item1.type == 1) {
											discountCouponListItem.mchName = item1.mchName
											discountCouponListItem.mchLogo = item1.mchLogo
											if (item1.endDate==null) {
												item1.endDate = "永久有效"
											} else {
												item1.endDate = this.formatDateAndTime(item1.endDate)
											}
											item1.tag = this.formatTag(item1.targetType)
											discountCouponListItem.couponList.push(item1)
										}
									}
								})
								discountCouponList.push(discountCouponListItem)
							})
						}
						if (exchangetShopList.length > 0) {
							exchangetShopList.map((item) => {
								let exchangetCouponListItem = {}
								exchangetCouponListItem.couponList = []
								res.data.data.map((item1) => {
									if (item1.mchName == item) {
										if (item1.type == 3) {
											exchangetCouponListItem.chk = false
											exchangetCouponListItem.mchName = item1.mchName
											exchangetCouponListItem.mchLogo = item1.mchLogo
											if (item1.endDate==null) {
												item1.endDate = '永久有效'
											} else {
												item1.endDate = this.formatDateAndTime(item1.endDate)
											}
											item1.tag = this.formatTag(item1.targetType)
											item1.chk = false
											item1.quantitys = 1 
											exchangetCouponListItem.couponList.push(item1)
										}
									}
								})
								exchangetCouponList.push(exchangetCouponListItem)
							})
						}
						console.log(exchangetCouponList)
						// console.log("接收优惠券的信息fullReductiontCouponList--" + JSON.stringify(fullReductionCouponList))
						// console.log("接收优惠券的信息discountCouponList--" + JSON.stringify(discountCouponList))
						// console.log("接收优惠券的信息exchangetCouponList--" + JSON.stringify(exchangetCouponList))
						this.setData({
							fullReductionCouponList: fullReductionCouponList,
							discountCouponList: discountCouponList,
							exchangetCouponList: exchangetCouponList
						})
					}
				}
			}
		).catch(error => {
			console.log(error)
		})
	},

	//  tab切换逻辑
	swichNav: function(e) {
		console.log(e)
		var that = this;

		if (this.data.currentTab === e.target.dataset.current) {
			return false;
		} else {
			that.setData({
				currentTab: e.target.dataset.current
			})
		}
	},

	bindChange: function(e) {

		var that = this;
		that.setData({
			currentTab: e.detail.current
		});

	},

	//优惠券去使用的点击事件
	useCoupon: function(e) {
		console.info("点击跳转到对应的页面")
		console.log(e)
		this.data.productId = e.currentTarget.dataset.id
		this.findClick()
	},

	//时间格式化器
	formatDateAndTime: function(value) {
		let date = new Date(value);
		let y = date.getFullYear();
		let MM = date.getMonth() + 1;
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate();
		d = d < 10 ? ('0' + d) : d;
		let h = date.getHours();
		let m = date.getMinutes();
		let s = date.getSeconds();
		return y + '-' + MM + '-' + d + " " + h + ":" + m + ":" + s;
	},

	findClick() {
    var _this = this
    find(_this.data.productId ).then(
      res => {
				console.log(res)
				if(res.data.products[0].minLimit > 0){
					_this.data.quantity = res.data.products[0].minLimit
				}else{
					_this.data.quantity = 1
				}
				_this.buyNowClick()
      }
    ).catch(error => {
      console.log(error)
    })
	},
	buyNowClick(){
		var _this = this
			let data = {}
					data.productId = _this.data.productId
					data.promotionId = ""
					data.quantity = _this.data.quantity
					data.uuid = app.globalData.uuid
				  console.log(data)
					buyNow(data).then(
						res => {
							if (res.type == 'success') {
								wx.navigateTo({
									url: '/pages/goods/submit/index',
									success: function(res) {},
									fail: function(res) {},
									complete: function(res) {},
								})
							}
						}
					).catch(error => {
						console.log(error)
						wx.showToast({
							title: error,
							icon: 'none',
							duration: 2000
						})
					})
	},
	chooseClick(e){
		var index = e.currentTarget.dataset.index
		var indexs = e.currentTarget.dataset.indexs
		console.log(this.data.exchangetCouponList)
		this.data.exchangetCouponList[indexs].couponList[index].chk = !this.data.exchangetCouponList[indexs].couponList[index].chk
		console.log(this.data.exchangetCouponList)
		this.setData({
			exchangetCouponList:this.data.exchangetCouponList
		})
	},
	useClick(){
		var _this = this
		var exchangetCouponList = []
		_this.data.exchangetCouponList.forEach(function(item){
			item.couponList.forEach(function(items){
				if(items.chk == true){
					var data = {
						id:items.id,
						quantity:items.quantitys
					}
					exchangetCouponList.push(data)
				}
			})
		})
		if(exchangetCouponList.length > 0){
			buyNowForCoupon(exchangetCouponList).then(
				res => {
					if (res.type == 'success') {
						wx.navigateTo({
							url: '/pages/goods/submit/index',
						})
					}
				}
			).catch(error => {
				wx.showToast({
					title: error.content,
					icon: 'none',
					duration: 2000
				})
			})
		}
	},
	numAdd(e){
		console.log(e)
		var _this = this
		var index = e.currentTarget.dataset.index
		var indexs = e.currentTarget.dataset.indexs
		if(this.data.exchangetCouponList[index].couponList[indexs].quantitys >= this.data.exchangetCouponList[index].couponList[indexs].stock){
			this.data.exchangetCouponList[index].couponList[indexs].quantitys = this.data.exchangetCouponList[index].couponList[indexs].stock
			wx.showToast({
				title: '剩余张数不足',
			})
		}else{
			this.data.exchangetCouponList[index].couponList[indexs].quantitys += 1
		}
		_this.setData({
			exchangetCouponList:_this.data.exchangetCouponList
		})
	},
	numReduce(e){
		var _this = this
		var index = e.currentTarget.dataset.index
		var indexs = e.currentTarget.dataset.indexs
		if(this.data.exchangetCouponList[index].couponList[indexs].quantitys <= 1){
			this.data.exchangetCouponList[index].couponList[indexs].quantitys = 1
			wx.showToast({
				title: '张数不能少于1',
			})
		}else{
			this.data.exchangetCouponList[index].couponList[indexs].quantitys -= 1
		}
		_this.setData({
			exchangetCouponList:_this.data.exchangetCouponList
		})
	},
	bindblur(e){
		var _this = this
		console.log(e)
		var index = e.currentTarget.dataset.index
		var indexs = e.currentTarget.dataset.indexs
		if(this.data.exchangetCouponList[index].couponList[indexs].quantitys < 1){
			this.data.exchangetCouponList[index].couponList[indexs].quantitys = 1
			wx.showToast({
				title: '张数不能少于1',
			})
		}
		if(this.data.exchangetCouponList[index].couponList[indexs].quantitys > this.data.exchangetCouponList[index].couponList[indexs].stock){
			this.data.exchangetCouponList[index].couponList[indexs].quantitys = this.data.exchangetCouponList[index].couponList[indexs].stock
			wx.showToast({
				title: '剩余张数不足',
			})
		}
		_this.setData({
			exchangetCouponList:_this.data.exchangetCouponList
		})
	},
	selectAllClick(e){
		var _this = this
		console.log(e)
		var index = e.currentTarget.dataset.index
		if(_this.data.exchangetCouponList[index].chk == false){
			_this.data.exchangetCouponList[index].chk = true
			_this.data.exchangetCouponList[index].couponList.forEach(function(item){
				item.chk = true
			})
		}else{
			_this.data.exchangetCouponList[index].chk = false
			_this.data.exchangetCouponList[index].couponList.forEach(function(item){
				item.chk = false
			})
		}
		_this.setData({
			exchangetCouponList:_this.data.exchangetCouponList
		})
	}
})
